package ru.autofan.logic.initialization;

import ru.autofan.domain.AuthRole;
import ru.autofan.domain.User;
import ru.autofan.form.RegistrationForm;
import ru.autofan.logic.RegistrationRequestService;
import ru.autofan.logic.RoleService;
import ru.autofan.logic.ServiceLocator;
import ru.autofan.logic.UserService;

public class SystemUserInitializer {

	private static final String SYSTEM_EMAIL = "system_email";
	
	private static final String SYSTEM_PASSWORD = "system_password";

	private ServiceLocator serviceLocator;
	
	public SystemUserInitializer() {
	}

	public ServiceLocator getServiceLocator() {
		return serviceLocator;
	}

	public void setServiceLocator(ServiceLocator serviceLocator) {
		this.serviceLocator = serviceLocator;
	}

	public void init() throws Exception {
		UserService userService = serviceLocator.getService(UserService.class);
		if (userService.findUserbyEmail(SYSTEM_EMAIL) == null) {
			RegistrationRequestService registrationRequestService = serviceLocator.getService(RegistrationRequestService.class);
			RegistrationForm request = new RegistrationForm();
			request.setEmail(SYSTEM_EMAIL);
			request.setPassword(SYSTEM_PASSWORD);
			
			String uuid = registrationRequestService.create(request);
			userService.registerUser(uuid);
			
			User admin = userService.findUserbyEmail(SYSTEM_EMAIL);
			
			admin.getRoles().add(serviceLocator.getService(RoleService.class).getRole(
					"ADMINISTRATOR", AuthRole.class));
		}
	}

}
